import { getOrderBit, batchRes } from "@/generic/Utils";
import { queryTrash, deleteTrash, restoreTrash, queryShare, deleteShare } from "./service";
import { queryUsers, } from "@/services/user";
import { SHARE_NEWS } from "./configs/share";

const FILE_MARK = {
    trash: 'trash',
    share: 'share',
}

const resultTrans = async (orgiData = []) => {

    const transFields = [];
    for (const item in SHARE_NEWS) {
        transFields.push({
            orgiKey: item, newKey: SHARE_NEWS[item].newKey, resKey: SHARE_NEWS[item].resKey
        });
    }
    
    for (const orgi of orgiData) {
        for (const item of transFields) {
            const { orgiKey, newKey, resKey } = item;
            const response = await queryUsers({ id: orgi[orgiKey]}, true);
            orgi[newKey] = response[resKey];
        }
    }

    return orgiData;
}

export default {
    namespace: 'fileManage',
    state: {
        MARK: null,
        currentUser: {},
        data: [],
        loading: true,
        checkedRows: [],
        currentPage: null,
        objInfo: {},
    },
    effects: {
        *methodAdapter({ payload, method }, { _, put, select }) { // payload = {method, ...}
            console.log("==>> methodAdapter is enter!", payload, method,)
            if (method) {
                yield put({type: 'updateLoading', payload: true});
                const requests = {
                    query: [queryTrash, queryShare],
                    add: [null, null],
                    delete: [deleteTrash, deleteShare],
                    update: [restoreTrash, null],
                };
                const fileManage = yield select(state => state.fileManage);
                let response = null;
                const _method = requests[method]
                if (!_method) return false;  // 不支持的method，则返回false
                // console.log("==>> fileManage.MARK!", fileManage.MARK)
                switch (fileManage.MARK) {
                    case FILE_MARK.share:
                        response = yield put({ type: method, request: _method[1], payload,  isTrans: true});
                        break;

                    default:
                        response = yield put({ type: method, request: _method[0], payload });
                        break;
                }

                return response
            }
        },

        *query({ request:queryRequest, payload = {}, isTrans = false }, { call, put }) {
            // console.log('===>> query', payload)
            if (queryRequest) {
                const response = yield call(queryRequest, payload, true);
                console.log('===>> response', response)
                let transRes = [];
                if (response.results) {
                    transRes = response.results;
                    if (isTrans) {
                        transRes = yield resultTrans(response.results);
                    }
                }
                console.log("==>> resultTrans", transRes)
                yield put({
                    type: 'updateData',
                    payload: transRes
                })
                return response;
            }
        },
        *delete({ request: deleteRequest, payload = {} }, { call, put }) {
            console.log("==..> delete", payload)
            //实现批量删除 or 单个删除
            // 锁住的文件不能删除 | 还未做 locked = fasle;
            const locked = false;

            if (!locked) {
                let response = null;
                if (payload.value && payload.value.empty) {  // 代表清空
                    response = yield call(deleteRequest);
                }
                else{
                    response = yield batchRes(deleteRequest, payload, call)
                }
                // console.log("==..> delete response", response)
                if (response.ok) {
                    yield put({ type: 'methodAdapter', method: 'query', payload: {} })
                }
                return response;
            }
            // statusText 中文必须解码，不然会报错。
            const init = { ok: false, status: 405, statusText: encodeURI("存在被锁住的文件") };
            return new Response(new Blob(), init)
        },
        *update({ request: updateRequest, payload }, { call, put }) {
            console.log("==..> userUpdate", payload)
            if (updateRequest) {
                let response = null;
                if (payload.value && payload.value.restore) {
                    response = yield call(updateRequest)
                }
                else {
                    response = yield batchRes(updateRequest, payload, call)
                }
                if (response.ok) {
                    yield put({ type: 'methodAdapter', method: 'query', payload: {} })
                }

                return response;
            }
        },

        *getNameById({ payload:id }, { call, put }) {

            if (id) {
                const response = yield call(queryUsers, { id, }, true)
                console.log("response===>> ", response)
                if (response.nickName) return response.nickName
                return false;
            }
        },
    },
    reducers: {
        updateMARK(state, { payload = null }) {
            console.log('==>> updateMARK', payload)
            return { ...state, MARK: payload }
        },

        updateData(state, { payload = [] }) {
            // data更新时，永远把checkedRows初始为[]
            // console.log('==>> updateData', payload)
            if (payload.length > 0) {
                const orderBit = getOrderBit(payload.length);
                orderBit && payload.forEach((item, i) => {
                    item.key = `${i + 1}`.padStart(orderBit, "0");
                })
            }
            return { ...state, data: payload, checkedRows: [], loading: false }
        },

        updateLoading(state, { payload }) {
            // console.log("===>> updateCheckedRows", payload)
            return { ...state, loading: payload }
        },

        updateCheckedRows(state, { payload = [] }) {
            // console.log("===>> updateCheckedRows", payload)
            return { ...state, checkedRows: payload }
        },

        updateCurrentPage(state, { payload }) {
            console.log("==>> updateCurrentPage", payload)
            let page = null;
            if (typeof (payload) == "undefined") {
                page = state.currentPage;
            }
            else {
                page = payload ? payload.mark : page;
            }
            return {
                ...state, currentPage: page,
                objInfo: payload ? payload.record : state.objInfo,
            }
        },
    },
}